package linkedList;

class MyLinkedList {
    Node node; //指针
    Node head;
    public MyLinkedList() {
        head = null;
    }

    public int get(int index) {
        if(head == null ){
            return -1;
        }
        node = head;
        while(index >0 && node.next != null){
            node = node.next;
            index--;
        }
        if(index > 0){return -1;}
        return node.val;
    }

    public void addAtHead(int val) {
        if(head == null){
            head = new Node();
            head.val = val;
            head.next = null;
        }
        else{
            Node newNode = new Node();
            newNode.val = val;
            newNode.next = head;
            head = newNode;
        }
    }

    public void addAtTail(int val) {
        if(head == null){
            head = new Node();
            head.val = val;
            head.next = null;
        }
        else{
            Node newNode = new Node();
            newNode.val = val;
            newNode.next = null;
            node = head;
            while(node.next != null){
                node = node.next;
            }
            node.next = newNode;
        }

    }

    public void addAtIndex(int index, int val) {
        if(index == 0){
            addAtHead(val);
        }
        node = head;
        while(index >1 && node.next != null){
            node = node.next;
            index--;
        }
        if(index > 1){return;}
        Node preNode = node;
        node = node.next;
        Node newNode = new Node();
        newNode.val = val;
        preNode.next = newNode;
        newNode.next = node;

    }

    public void deleteAtIndex(int index) {
        if(index == 0){
            head = head.next;
            return;
        }
        node = head;
        while(index >1 && node.next != null){
            node = node.next;
            index--;
        }
        if(index > 1){return;}
        node.next = node.next.next;

    }
    static class Node{
        Node next;
        int val;
    }
}
